import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Lost from '../views/Lost.vue'
import Found from '../views/Found.vue'
import Publish from '../views/Publish.vue'
import Guide from '../views/Guide.vue'
import UserCenter from '@/views/UserCenter.vue'
import UserProfileView from '@/views/user/UserProfileView.vue'
import UserAvatarView from '@/views/user/UserAvatarView.vue'
import UserPostsView from '@/views/user/UserPostsView.vue'
import UserNotificationsView from '@/views/user/UserNotificationsView.vue'
import UserSecurityView from '@/views/user/UserSecurityView.vue'
import ItemDetail from '../views/ItemDetail.vue'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/lost',
    name: 'Lost',
    component: Lost
  },
  {
    path: '/found',
    name: 'Found',
    component: Found
  },
  {
    path: '/publish',
    name: 'Publish',
    component: Publish,
    meta: { requiresAuth: true }
  },
  {
    path: '/guide',
    name: 'Guide',
    component: Guide
  },
  {
    path: '/user',
    component: UserCenter,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/user/profile'
      },
      {
        path: 'profile',
        component: UserProfileView,
        name: 'UserProfile'
      },
      {
        path: 'avatar',
        component: UserAvatarView,
        name: 'UserAvatar'
      },
      {
        path: 'posts',
        component: UserPostsView,
        name: 'UserPosts'
      },
      {
        path: 'notifications',
        component: UserNotificationsView,
        name: 'UserNotifications'
      },
      {
        path: 'security',
        component: UserSecurityView,
        name: 'UserSecurity'
      }
    ]
  },
  {
    path: '/lost/:id',
    name: 'LostItemDetail',
    component: ItemDetail,
    meta: {
      requiresAuth: false,
      title: '寻物启事详情'
    }
  },
  {
    path: '/found/:id',
    name: 'FoundItemDetail',
    component: ItemDetail,
    meta: {
      requiresAuth: false,
      title: '失物招领详情'
    }
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 添加全局导航守卫
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const isLoggedIn = !!localStorage.getItem('token');

  if (requiresAuth && !isLoggedIn) {
    // 保存用户试图访问的路径，登录成功后可以重定向回来
    localStorage.setItem('redirectUrl', to.fullPath);

    // 显示消息
    ElMessage.warning('请先登录');

    // 重定向到首页
    next('/');
  } else {
    next();
  }
});

export default router 